<template>
    <div class="app-container">
        <div class="updateCoupon">
            <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
                size="default" status-icon>
                <el-form-item label="优惠券类型">
                    <el-select v-model="couponVal.type" class="input1" placeholder="请选择" size="default" @change="change">
                        <el-option v-for="item in options1" :key="item.type" :label="item.label" :value="item.type" />
                    </el-select>
                </el-form-item>
                <el-form-item label="优惠券名称:" required prop="name">
                    <el-input size="default" v-model="ruleForm.name" placeholder="请输优惠券名称" class="input1" />
                </el-form-item>

                <el-form-item label="适用平台">
                    <el-select v-model="platformVal.type" class="input1" placeholder="请选择" size="default" @change="change2">
                        <el-option v-for="item in options2" :key="item.type" :label="item.label" :value="item.type" />
                    </el-select>
                </el-form-item>
                <el-form-item label="总发行量：:" required prop="publishCount">
                    <el-input size="default" v-model="ruleForm.publishCount" placeholder="只能输入正整数" class="input1" />
                </el-form-item>
                <el-form-item label="面额:" required prop="amount">
                    <el-input v-model="ruleForm.amount" placeholder="Please input" class="input-with-select">
                        <template #append>
                            元
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item label="每人限领:" required prop="perLimit">
                    <el-input v-model="ruleForm.perLimit" placeholder="Please input" class="input-with-select">
                        <template #append>
                            张
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item label="使用门槛:" required prop="minPoint">

                    <el-input v-model="ruleForm.minPoint" placeholder="只能输入正整数" class="input-with-select">
                        <template #prepend>
                            满
                        </template>
                        <template #append>
                            元可用
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item label="领取日期：" required prop="enableTime">
                    <el-date-picker v-model="ruleForm.enableTime" type="date" placeholder="请选择时间" :size="size"
                        format='YYYY-MM-DD' @change="dateChange" />
                </el-form-item>
                <el-form-item label="到期时间" required prop="endTime">
                    <el-date-picker v-model="ruleForm.startTime" type="date" placeholder="请选择时间" :size="size"
                        format='YYYY-MM-DD' @change="dateChange" />
                    <span>&nbsp;&nbsp;至 &nbsp;&nbsp;</span>
                    <el-date-picker v-model="ruleForm.endTime" type="date" placeholder="请选择时间" :size="size"
                        format='YYYY-MM-DD' @change="dateChange" />
                </el-form-item>
                <el-form-item label="可使用商品：">
                    <el-radio-group v-model="radioVal.label" :active-value="1" :inactive-value="0" @change="radioChange">
                        <el-radio-button label="全场通用" />
                        <el-radio-button label="指定分类" />
                        <el-radio-button label="指定商品" />
                    </el-radio-group>
                </el-form-item>
                <!-- 展示指定分类 -->
                <el-form-item v-if="ruleForm.useType == 1">
                    <el-cascader v-model="(WithChildren as any)" :options="options3" @change="handleChange" />
                    <el-button type="primary" @click="addChoose()">添加</el-button>
                    <el-table :data="classifyData" border style="width: 100%">
                        <el-table-column label="活动分类">
                            <template #default="{ row }">
                                {{ row.label }}>{{ row.children[0].label }}
                            </template></el-table-column>>
                        <el-table-column width="260" prop="label" label="操作">
                            <template #default="{ row }">
                                <el-button link type="primary" size="small" @click="deleteFn(row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>
                <!-- 自动补全输入框2 -->
                <el-form-item v-if="ruleForm.useType == 2">

                    <Autocomplete @hdAdd="hdAdd" />



                    <el-table :data="classifyData" border style="width: 80%;margin-top: 20px;">
                        <el-table-column label="活动分类">
                            <template #default="{ row }">
                                {{ row.label }}>{{ row.children[0].label }}
                            </template></el-table-column>>
                        <el-table-column width="260" prop="label" label="操作">
                            <template #default="{ row }">
                                <el-button link type="primary" size="small" @click="deleteFn(row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>

                <el-form-item label=" 广告备注" prop="note">
                    <el-input v-model="ruleForm.note" type="textarea" class="textarea" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">
                        确认
                    </el-button>
                    <el-button @click="reset(ruleFormRef)" v-if="!route.query.id">
                        重置
                    </el-button>

                </el-form-item>
            </el-form>
        </div>
    </div>
</template>
  
<script lang="ts" setup>
import * as http from '@/request/http';
import { reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import Autocomplete from './components/Autocomplete.vue'
const route = useRoute()
const router = useRouter()
const ruleForm = reactive<MyCouponListDetailModel>({
    id: 0,
    type: 0,
    name: '',
    platform: 0,
    count: 0,
    amount: 0,
    perLimit: 0,
    minPoint: 0,
    startTime: '',
    endTime: '',
    useType: 0,
    note: '',
    publishCount: 0,
    useCount: 0,
    receiveCount: 0,
    enableTime: '',
    code: '',
    memberLevel: '',
    productRelationList: [],
    productCategoryRelationList: []

})
let classifyData = ref<[]>([])
let options3 = ref<any>([])
const WithChildren = ref<IWithChildrenR[]>([])
http.updateCoupon.WithChildren().then(res => {
    WithChildren.value = res.data
    options3 = WithChildren.value.map((item: any, index: any) => {
        return { label: item.name, value: item.id, children: [{ value: item.children[index]?.id, label: item.children[index]?.name }] }
    })
})

if (Number(route.query.id)) {
    http.coupon.getCouponListById(Number(route.query.id)).then(res => {
        if (res.code == 200) {
            Object.assign(ruleForm, res.data)
            couponVal.type = ruleForm.type
            platformVal.type = ruleForm.platform
            radioVal.type = ruleForm.useType
        }
    })
}

const couponVal = reactive({
    type: 0,
    label: '全场赠券'
})
const platformVal = reactive({
    type: 0,
    label: '全场通用',
})
const radioVal = reactive({
    type: 0,
    label: '全平台',
})
const options1 = [
    {
        type: 0,
        label: '全场赠券',
    },
    {
        type: 1,
        label: '会员赠券',
    },
    {
        type: 2,
        label: '购物赠券',
    },
    {
        type: 3,
        label: '注册赠券',
    },
]
const options2 = [
    {
        type: 0,
        label: '全平台',
    },
    {
        type: 1,
        label: '移动平台',
    },
    {
        type: 2,
        label: 'pc平台',
    }
]
const reset = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}
// let productCategoryRelationList = ref<IProductCategoryRelationListModel[]>([])
// let newArr: [] = []
let newObj: any = ref('')
const handleChange = (val: any) => {
    const index = options3.findIndex((item: any) => {
        return item.value == val[0]
    })
    newObj = options3[index]
    options3.forEach((e: any) => {
        if (newObj.value == e.id) {
            ruleForm.productCategoryRelationList.push(e)
        }
    });
    // ruleForm.productCategoryRelationList = newObj
}

const addChoose = () => {
    console.log(classifyData);
    if (newObj) {
        classifyData.value.push(newObj as never)
    }

    console.log(newObj);
}
const deleteFn = (row: any) => {
    // console.log(row);
    const i = classifyData.value.findIndex((item: any) =>
        item.value == row.value
    )
    classifyData.value.splice(i, 1)
}
const size = ref<'default' | 'large' | 'small'>('default')
const dateChange = () => {
    console.log(123);
}
const change = () => {
    couponVal.label = couponVal.type == 0 ? '全场赠券' : couponVal.type == 1 ? '会员赠券' : couponVal.type == 2 ? '购物赠券' : '注册赠券'
    ruleForm.type = couponVal.type
    console.log(ruleForm.type);
}
const change2 = () => {
    platformVal.label = platformVal.type == 0 ? '全平台' : platformVal.type == 1 ? '移动平台' : '注册pc平台券'
    ruleForm.platform = platformVal.type
    console.log(ruleForm.platform);
}
const radioChange = () => {
    radioVal.type = radioVal.label == '全场通用' ? 0 : radioVal.label == '指定分类' ? 1 : 2
    ruleForm.useType = radioVal.type
    console.log(ruleForm.useType);
}

const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules<ICouponCreatePrams>>({
    name: [
        { required: true, message: '请输入广告名称', trigger: 'blur' },
    ],
    startTime: [
        {
            type: 'date',
            required: true,
            message: '请选择时间',
            trigger: 'change',
        },
    ],
    endTime: [
        {
            type: 'date',
            required: true,
            message: '请选择时间',
            trigger: 'change',
        },
    ],
    note: [
        {
            required: true,
            message: '请输入备注',
            trigger: 'blur',
        },
    ],

})
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, _fields) => {
        if (valid) {
            ElMessageBox.confirm(
                '是否提交数据 ? ',
                '提示',
                {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(() => {
                    http.coupon.ICouponUpdateById(ruleForm).then(
                        res => {
                            if (res.code == 200) {
                                ElMessage.success('添加成功');
                                router.push('coupon')
                            }
                        }
                    )
                })
                .catch(() => {
                    ElMessage.error('添加失败');

                })
        } else {
            ElMessage.success('取消添加');

        }
    })
}

// -----------下拉菜单
const hdAdd = (val: any) => {
    console.log(val);

}
</script>
  
<style scoped lang="less">
.updateCoupon {
    display: flex;
    justify-content: center;
    margin: 0 auto;
    min-height: 650px;
    width: 990px;
    border: 1px solid #ccc;
    overflow: hidden;
    padding: 20px;

    &::-webkit-scrollbar {
        width: 0;
    }
}

:deep(.input1) {
    width: 340px;
}

:deep(.textarea) {
    width: 340px;
}

.example-showcase .el-dropdown-link {
    cursor: pointer;
    color: var(--el-color-primary);
    display: flex;
    align-items: center;
}
</style>
  
  
  